import { Injectable, OnApplicationBootstrap } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { Button } from '@/modules/button/entities/button.entity'
import { CreateButtonDto, FindButtonDto, UpdateButtonDto } from './dto/button.dto'

@Injectable()
export class ButtonService implements OnApplicationBootstrap {
  constructor(
    @InjectRepository(Button)
    private buttonRepository: Repository<Button>,
  ) {}

  async onApplicationBootstrap() {
    const exists = await this.findOne({})
    if (!exists) {
      await this.create({})
      console.log('按钮配置已初始化')
    }
  }

  create(createData: CreateButtonDto) {
    return this.buttonRepository.save(createData)
  }

  async findOne(data: FindButtonDto) {
    return await this.buttonRepository.findOneBy(data)
  }

  async update(buttonId: number, updateData: UpdateButtonDto) {
    return this.buttonRepository.update(buttonId, {
      ...updateData,
      buttonId: undefined,
    })
  }
}
